// 引入Three.js
import * as THREE from 'three';
// 引入glTF模型加载库GLTFLoader.js
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from '../public/three/examples/jsm/loaders/DRACOLoader.js';
import TWEEN from '@tweenjs/tween.js';

const loader = new GLTFLoader();
const path = 'public/blender/house.gltf';
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('three/examples/jsm/libs/draco/gltf/'); // 设置 DRACOLoader 的解码器路径，根据实际路径填写
loader.setDRACOLoader(dracoLoader); // 将 DRACOLoader 实例传递给 GLTFLoader

const model = new THREE.Group();
let door_isopen = false; // 全局标志位
let doorObject = null;
let doorPivot = null; // 全局变量


loader.load(path, function (gltf) {
    gltf.scene.traverse((child) => {
        if (child.name === 'door') {
            doorObject = child;
        }
    });

    if (doorObject) {
        // 创建 pivot 对象并设置为门的旋转中心
        doorPivot = new THREE.Object3D();
        model.add(doorPivot);
        doorPivot.add(doorObject);

        const doorBox = new THREE.Box3().setFromObject(doorObject);
        const doorSize = doorBox.getSize(new THREE.Vector3());
        const pivotPosition = new THREE.Vector3();
        doorBox.getCenter(pivotPosition);
        pivotPosition.x += doorSize.x / 2;

        doorPivot.position.copy(pivotPosition);
        doorObject.position.sub(pivotPosition);
    }

    model.add(gltf.scene);
});
//控制门转动
function rotateDoor(isOpen) {
    if (!doorObject || !doorPivot) {
        console.error('doorObject 或 doorPivot 未加载完成');
        return;
    }

    const targetRotation = isOpen ? Math.PI / 2 : 0;

    // 执行旋转动画
    new TWEEN.Tween(doorPivot.rotation)
        .to({ y: targetRotation }, 1000)
        .easing(TWEEN.Easing.Quadratic.InOut)
        .onComplete(() => {
            door_isopen = isOpen === 1;
        })
        .start();
}

export { model, doorObject, rotateDoor, door_isopen };
